<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NSpace align="center">
          类型筛选:
          <NSelect :options="noticeTypeCodeList" placeholder="请选择类型筛选" clearable style="width: 200rem"
            v-model:value="paginationReactive.noticeTypeCode" filterable  />
          <NButton type="primary" style="width: 78rem" ghost
            @click="() => ((paginationReactive.page = 1), getNoticeList())">
            查询
          </NButton>
        </NSpace>
        <NButton type="primary" style="width: 120rem" @click="readAll" :loading="readLoading" ghost>
          全部已读
        </NButton>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :columns="columns" :data="tableData" :pagination="false"
        :loading="tableLoading" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
</template>
<script setup lang="ts">
import { h, reactive, onMounted, ref, watch, onDeactivated } from 'vue'
import { NSpace, NButton, NDataTable, NPagination, NSelect, useMessage } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import TableView from '@/components/TableView.vue'
import router from '@/router'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import type { UserModel } from '@/api/userCenter'
import { useRoute } from 'vue-router'
import { userCenterStore } from '@/stores/notice'
import { useViewerStore } from '@/views/OA/Common/store'
import { RecordType } from '@/router/utils'

const useOAStore = useViewerStore()
const useStore = userCenterStore()
const message = useMessage()
const route = useRoute()
const noticeTypeCodeList = [
  { label: '全部', value: 'A1001' },
  { label: '审批-审核通过', value: 'A1002' },
  { label: '审批-被否决', value: 'A1003' },
  { label: '收发文-收文通知', value: 'A1004' },
  { label: '工资单-通知', value: 'A1005' },
  { label: '调休-即将过期', value: 'A1006' },
  { label: '生日-提醒', value: 'A1007' },
  { label: '盖章确认提醒', value: 'A1008' },
]

const columns: DataTableColumns = [
  {
    title: '类型',
    key: 'noticeTypeCodeName',
    width: 80,
    align: useOAStore.isCenter
  },
  {
    title: '备注',
    key: 'title',
    width: 300,
    align: useOAStore.isCenter
  },
  {
    title: '内容',
    key: 'content',
    width: 40,
    align: useOAStore.isCenter
  },
  {
    title: '时间',
    key: 'createTime',
    width: 80,
    align: useOAStore.isCenter
  },
  {
    title: '状态',
    key: 'readFlag',
    width: 40,
    render({ readFlag }) {
      return readFlag == 1 ? '已读' : '未读'
    },
    align: useOAStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    align: useOAStore.isCenter,
    width: 60,
    fixed: 'right',
    render: (row: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: async () => {
            RecordType.setRouteNameTypeFalse(row.code)
            const path = jumpRouterList.value.find((it: any) => it.code == row.source)?.routeOne
            if (path) router.push({ path, query: { id: row.sourceId as never, redirect: route.fullPath } })
            else if (row.source == 'A0590') router.push({ path: '/OA/UserCenter/BirthdayInfo', query: { id: row.sourceId as never, redirect: route.fullPath } })
            else return message.error('功能正在开发中')
            await sendRequest<HttpResponse<UserModel>>({
              module: 'userCenter',
              api: 'noticeRead',
              override: {
                params: {
                  id: row.id
                }
              }
            })
            useStore.getTopCount()
          }
        },
        {
          default: () => '详情'
        }
      )
    ]
  }
]
// 上一页下一页
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 50,
  noticeTypeCode: null, //类型
  onChange: (page: number) => {
    paginationReactive.page = page
    getNoticeList()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    getNoticeList()
  }
})
// 全部已读
const readLoading = ref(false)
const readAll = async () => {
  readLoading.value = true
  const [error, res] = await sendRequest<HttpResponse<UserModel>>({
    module: 'userCenter',
    api: 'noticeReadAll'
  })
  readLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success('已读成功')
  useStore.getTopCount()
  getNoticeList()
}
// 获取列表
const tableData = ref([])
const tableLoading = ref(false)
const getNoticeList = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponse<UserModel>>({
    module: 'userCenter',
    api: 'noticeList',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        noticeTypeCode: paginationReactive.noticeTypeCode
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  tableData.value = res.data.list
  paginationReactive.itemCount = res.data.totalCount
}
//获取需要跳转的路由
const jumpRouterList: any = ref([])
const getJumpRouterList = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'userCenter',
    api: 'getJumpRoute'
  })
  if (error) return message.error(error.message)
  jumpRouterList.value = res.data
}

onMounted(() => {
  getJumpRouterList()
})

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,getNoticeList())
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route,
  () => {
    if (route.path == '/OA/UserCenter/MessageNotice') {
      getNoticeList()
      window.addEventListener('keyup', keyUpDown, false)  // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>
<style scoped lang="scss">
.table {
  padding: 29rem 30rem 42rem;
}
</style>
